<template>
  <a-card :bordered="false">
    <template>
      <a-steps :current="currentIndex">
        <a-step title="编辑任务" sub-title="编辑常规信息"/>
        <a-step title="摄像机" sub-title="勾选摄像机"/>
        <a-step title="任务明细" sub-title="确认任务"/>
        <a-step title="完成" sub-title="完成任务配置"/>
      </a-steps>
      <div>
        <div style="min-height: 680px;">
          <a-row :gutter="24">
            <div v-if="currentIndex == 0">
              <div style="height: 100px;">
              </div>
              <a-form :form="form">
                <a-col :md="12" :sm="12">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="任务名称">
                    <a-input placeholder="任务名称" v-decorator="['name', validatorRules.name]"/>
                  </a-form-item>
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="任务描述">
                    <a-textarea placeholder="任务描述" v-decorator.trim="[ 'taskDesc']"/>
                  </a-form-item>
                  <!--                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="磁盘位置">-->
                  <!--                    <a-input placeholder="磁盘位置" v-model="taskInfo.taskName"/>-->
                  <!--                  </a-form-item>-->
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="启用状态" name="启用状态">
                    <a-switch
                        v-decorator.trim="['used', {rules: [{required: true, message: '请输入选择'}],valuePropName: 'checked'}]"/>
                  </a-form-item>
                </a-col>
                <a-col :md="12" :sm="12">
                  <a-form-item label="任务类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-radio-group v-decorator.trim="['typeId',  validatorRules.typeId]" button-style="solid" @change="changeTypeId">
                      <a-radio-button value="0">
                        单次
                      </a-radio-button>
                      <a-radio-button value="4">
                        长期
                      </a-radio-button>
<!--                      <a-radio-button value="3">-->
<!--                        月-->
<!--                      </a-radio-button>-->
<!--                      <a-radio-button value="2">-->
<!--                        周-->
<!--                      </a-radio-button>-->
<!--                      <a-radio-button value="1">-->
<!--                        日-->
<!--                      </a-radio-button>-->
                    </a-radio-group>
                  </a-form-item>
                  <a-form-item  v-if="form.getFieldValue('typeId') == 0" label="开始时间点" :labelCol="labelCol"
                                :wrapperCol="wrapperCol">
                    <a-range-picker
                        size="small"
                        :show-time="{ format: 'HH:mm:ss' }"
                        format="YYYY-MM-DD HH:mm:ss"
                        :placeholder="['开始时间', '结束时间']"
                        :disabled-date="disabledDate"
                        v-decorator="['rangeValue', validatorRules.rangeValue]"
                    />
                  </a-form-item>
<!--                  <a-form-item v-if="form.getFieldValue('typeId') == 0" label="开始时间点" :labelCol="labelCol"-->
<!--                               :wrapperCol="wrapperCol">-->
<!--                    <a-date-picker show-time v-decorator="['startDateTime', validatorRules.startDateTime]"-->
<!--                                   format="YYYY-MM-DD HH:mm:ss"/>-->
<!--                  </a-form-item>-->
<!--                  <a-form-item v-if="form.getFieldValue('typeId') == 0" label="结束时间点" :labelCol="labelCol"-->
<!--                               :wrapperCol="wrapperCol">-->
<!--                    <a-date-picker show-time v-decorator="['endDateTime', validatorRules.endDateTime]"-->
<!--                                   format="YYYY-MM-DD HH:mm:ss"/>-->
<!--                  </a-form-item>-->
<!--                  <a-form-item-->
<!--                      v-if="form.getFieldValue('typeId') != 0"-->
<!--                      label="开始时间"-->
<!--                      :labelCol="labelCol"-->
<!--                      :wrapperCol="wrapperCol"-->
<!--                  >-->
<!--                    <a-time-picker-->
<!--                        format="HH:mm:ss"-->
<!--                        v-decorator="['startDateTime', validatorRules.startDateTime]"-->
<!--                    />-->
<!--                  </a-form-item>-->
<!--                  <a-form-item-->
<!--                      v-if="form.getFieldValue('typeId') != 0"-->
<!--                      label="结束时间"-->
<!--                      :labelCol="labelCol"-->
<!--                      :wrapperCol="wrapperCol"-->
<!--                  >-->
<!--                    <a-time-picker-->
<!--                        format="HH:mm:ss"-->
<!--                        v-decorator="['endDateTime', validatorRules.endDateTime]"-->
<!--                    />-->
<!--                  </a-form-item>-->
                  <!--                  <a-form-item label="最长录制时长：" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
                  <!--                    <a-input-number :min="0" :max="30"/>-->
                  <!--                  </a-form-item>-->
                </a-col>
              </a-form>
            </div>
            <div v-if="currentIndex == 1" style="margin-top: 20px">
              <div class="table-page-search-wrapper">
                <a-form layout="inline">
                  <a-row :gutter="24">
                    <a-col :md="6" :sm="8">
                      <a-form-item label="设备名称">
                        <a-input placeholder="请输入设备名称查询" v-model="queryParam.name"></a-input>
                      </a-form-item>
                    </a-col>
<!--                    <a-col :md="6" :sm="8">-->
<!--                      <a-form-item label="设备型号:">-->
<!--                        <a-select placeholder="请选择设备型号" v-model="queryParam.modelId">-->
<!--                          <a-select-option v-for="item in modelList" :key="item.modelId" :value="item.modelId">-->
<!--                            {{item.name}}-->
<!--                          </a-select-option>-->
<!--                        </a-select>-->
<!--                      </a-form-item>-->
<!--                    </a-col>-->
                    <a-col :md="6" :sm="8">
                      <a-form-item label="是否在线:">
                        <a-select placeholder="请选择是否在线" showSearch showArrow optionFilterProp="children"
                                  :getPopupContainer="(node) => node.parentNode"
                                  :defaultActiveFirstOption="false" v-model="queryParam.online">
                          <a-select-option value="1">是</a-select-option>
                          <a-select-option value="0">否</a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
<!--                    <a-col :md="6" :sm="8">-->
<!--                      <a-form-item label="所属域:">-->
<!--                        <a-select placeholder="请选择所属域" showSearch showArrow optionFilterProp="children"-->
<!--                                  :getPopupContainer="(node) => node.parentNode" :defaultActiveFirstOption="false"-->
<!--                                  v-model="queryParam.cameraRegionId">-->
<!--                          <a-select-option v-for="item in regionIdList" :key="item.rescueId"-->
<!--                                           :value="item.regionIdName">{{ item.regionIdName }}-->
<!--                          </a-select-option>-->
<!--                        </a-select>-->
<!--                      </a-form-item>-->
<!--                    </a-col>-->

                    <a-col :md="6" :sm="8">
                      <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
												<a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
												<a-button type="primary" @click="resetParam" icon="reload" style="margin-left: 8px">重置</a-button>
                      </span>
                    </a-col>
                  </a-row>
                </a-form>
              </div>
              <div>
                <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
                  <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a
                    style="font-weight: 600">{{ selectedRowKeys.length }}</a>项&nbsp;&nbsp;
                  <a style="margin-left: 24px" @click="onClearSelected">清空</a>
                </div>

                <a-table ref="table" bordered size="middle" rowKey="cameraId" :columns="columns" :dataSource="dataSource"
                         :pagination="ipagination" :loading="loading"
                         :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                         @change="handleTableChange">
                </a-table>
              </div>
            </div>

            <div v-if="currentIndex == 2" style="margin-top: 20px">
              <a-table ref="editTable" :columns="caremaColumns" :data-source="data" bordered>
                <template
										v-for="col in ['name']"
										:slot="col"
										slot-scope="text, record"
                >
                  <div :key="col">
                    <a-input
                        v-if="record.editable"
                        style="margin: -5px 0"
                        :value="text"
                        @change="e => handleChange(e.target.value, record.key, col)"
                    />
                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </template>
								<template slot="operation" slot-scope="text, record">
                  <div class="editable-row-operations">
                  <span v-if="record.editable">
                    <a @click="() => save(record.key)">保存</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确认取消编辑?" @confirm="() => cancel(record.key)">
                      <a>取消</a>
                    </a-popconfirm>
                  </span>
                    <span v-else>
                    <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑名称</a>
                  </span>
                  </div>
                </template>
              </a-table>
            </div>

            <div v-if="currentIndex == 3" style="text-align: center;">
              <div style="height: 200px"></div>
              <template>
                <a-space style="margin: 0 auto">
                  <a-spin size="large" tip="配置中... "/>
                </a-space>
              </template>
            </div>
          </a-row>
        </div>
        <div style="text-align: center">
          <span style="overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" :disabled="currentIndex == 0 || currentIndex == 3 " @click="preStep"
                          icon="swap-left">上一步</a-button>
                <a-button type="primary" :disabled="currentIndex == 3" @click="nextStep" icon="swap-right"
                          style="margin-left: 8px">下一步</a-button>
          </span>
        </div>
      </div>
    </template>
  </a-card>
</template>

<script>
import {
  getAction,
  postAction
} from '@/api/manage'
import {getFileAccessHttpUrl} from '@/api/manage';
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import JInput from '@/components/jeecg/JInput'
import moment from "moment";
import pick from "lodash.pick";

const caremaColumns = [
  {
    title: '任务名称',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '摄像机名称',
    dataIndex: 'cameraName',
    scopedSlots: { customRender: 'cameraName' },
  },
  {
    title: '周期信息',
    dataIndex: 'typeId',
    scopedSlots: { customRender: 'typeId' },
    customRender: function(text) {
      if (text == 0) {
        return "单次"
      } else if (text == 4) {
        return "长期"
      }
    }
  },
  {
    title: '开始时间点',
    dataIndex: 'startDateTime',
    scopedSlots: { customRender: 'startDateTime' },
  },
  {
    title: '结束时间点',
    dataIndex: 'endDateTime',
    scopedSlots: { customRender: 'endDateTime' },
  },
  {
    title: '编辑任务名称',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' },
  },
];

let data = [];


export default {
  name: "DevChannelRecord",
  mixins: [JeecgListMixin],
  components: {
    JInput,
  },
  data() {
    return {
      queryParam: {
        cameraRegionId: ''
      },
      cacheData: [],
      // 阻止页面初始化 调用数据列表接口
      disableMixinCreated: true,
      data,
      caremaColumns,
      editingKey: '',
      currentIndex: 0,
      form: this.$form.createForm(this),
      addRecordTaskInfo: {},
      description: '这是设备通道录像信息页面',
      dataSource: [],
      model: {},
      columns: [
        /*{
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },*/
        {
          title: '摄像机名称',
          align: "center",
          dataIndex: 'name',
        },
        // {
        //   title: '所属设备',
        //   align: "center",
        //   dataIndex: 'nickName',
        // },
        {
          title: '摄像机描述',
          align: "center",
          dataIndex: 'cameraDesc',
        },
        {
          title: '摄像机地点',
          align: "center",
          dataIndex: 'location',
        },
        {
          title: '是否在线',
          align: "center",
          dataIndex: 'online',
          customRender: function(text) {
            if (text == 1) {
              return "是"
            } else if (text == 0) {
              return "否"
            }
          }
        },
        {
          title: '启用状态',
          align: "center",
          dataIndex: 'used',
          customRender: function(text) {
            if (text == 1) {
              return "启用"
            } else if (text == 0) {
              return "禁用"
            }
          }
        },
        {
          title: '域信息',
          align: "center",
          dataIndex: 'regionId',
          customRender: function(text) {
            return "本域"
          }
        },
        {
          title: '更新时间',
          align: "center",
          dataIndex: 'updateTime',
        },
        {
          title: '创建时间',
          align: "center",
          dataIndex: 'createTime',
        }
      ],
      validatorRules: {
        name: {
          rules: [{
            required: true,
            message: '请输入任务名称!'
          }]
        },
        typeId: {
          rules: [{
            required: true,
            message: '请选择任务类型!'
          }]
        },
        rangeValue: {
          rules: [{
            required: true,
            message: '请选择录像时间段!'
          }]
        },
        startDateTime: {
          rules: [{
            required: true,
            message: '请选择开始时间!'
          }]
        },
        endDateTime: {
          rules: [{
            required: true,
            message: '请选择结束时间!'
          }]
        },
      },
      rangeValue: [],
      regionIdList: [{
        regionIdName: "44010200492000000001",
        userType: 1
      },
        {
          regionIdName: "4401020049",
        },],
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 5
        },
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 16
        },
      },
      url: {
        list: "/dev/camera/all-page",
        addRecord: "/record/add",
      },
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  methods: {
    handleMenuClick(e) {
      if (e.key == 1) {
        this.batchDel();
      }
    },
    resetParam() {
      this.queryParam = {}
      this.queryParam.userType = undefined
      this.loadData(1)
    },
    // **************************************************************************************************************
    // 上一步
    preStep() {
      let that = this
      console.log(that.model)
      if (that.currentIndex == 1) {
        console.log("rangeValue", that.model.rangeValue)
        that.form.resetFields();
        that.$nextTick(() => {
          that.form.setFieldsValue(pick(that.model, 'name', 'taskDesc', 'typeId', 'rangeValue'))
        });
        this.currentIndex = this.currentIndex - 1
      }

      if (that.currentIndex == 2) {
        this.currentIndex = this.currentIndex - 1
        data.length = 0;
        this.cacheData = 0;
        this.loadData(1);
      }
    },
    // 下一步
    nextStep() {
      console.log(this.form.getFieldValue('rangeValue'))
      /* table选中keys*/
      console.log(this.selectedRowKeys)
      /* table选中records*/
      console.log(this.selectionRows)

      if (this.currentIndex == 0) {
        let taskId = this.form.getFieldValue('typeId');
        if (taskId == 0) {
          this.form.validateFields(['name', 'typeId', 'rangeValue'],(err, values) => {
            console.log(values)
            console.log("err", err)
            if (!err) {
              this.model = Object.assign(this.model, values);
              this.currentIndex = this.currentIndex + 1
              this.loadData(1);
              return
            }
          })
        }
        if (taskId == 4) {
          this.form.validateFields(['name', 'typeId'],(err, values) => {
            console.log(values)
            console.log("err", err)
            if (!err) {
              this.model = Object.assign(this.model, values);
              this.currentIndex = this.currentIndex + 1
              this.loadData(1);
              return
            }
          })
        }
        return
      }
      if (this.currentIndex == 1) {
        if (this.selectedRowKeys.length == 0) {
          this.$message.warning('请勾选需要执行任务的摄像机')
          return
        } else {
          let rows = this.selectionRows
          console.log("let rows = this.selectionRows", this.selectionRows)
          this.data.length = 0;
          this.editingKey = '';
          for (let i = 0; i < rows.length; i++) {
            let typeId = this.form.getFieldValue('typeId')
            if (typeId == 0) {
              this.data.push({
                key: i.toString(),
                name: `${this.form.getFieldValue('name')}_${rows[i].name}`,
                cameraName: `${rows[i].name}`,
                cameraId: `${rows[i].cameraId}`,
                typeId: this.form.getFieldValue('typeId'),
                startDateTime: this.form.getFieldValue('rangeValue')[0].format('YYYY-MM-DD HH:mm:ss'),
                endDateTime: this.form.getFieldValue('rangeValue')[1].format('YYYY-MM-DD HH:mm:ss'),
              });
            }
            if (typeId == 4) {
              this.data.push({
                key: i.toString(),
                name: `${this.form.getFieldValue('name')}_${rows[i].name}`,
                cameraName: `${rows[i].name}`,
                cameraId: `${rows[i].cameraId}`,
                typeId: this.form.getFieldValue('typeId'),
              });
            }
          }
          this.$nextTick(() => {
            this.cacheData = this.data.map(item => ({ ...item }));
          })
          this.currentIndex = this.currentIndex + 1
          return
        }
      }
      if (this.currentIndex == 2) {
        this.currentIndex = this.currentIndex + 1
        // 发送新增录像信息
        this.addRecordTask();
      }
    },
    onClearSelected() {

    },
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.find(item => key === item.key);
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    edit(key) {
      const newData = [...this.data];
      const target = newData.find(item => key === item.key);
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    save(key) {
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.find(item => key === item.key);
      const targetCache = newCacheData.find(item => key === item.key);
      console.log(target)
      console.log(targetCache)
      if (target && targetCache) {
        delete target.editable;
        console.log("newData", newData)
        this.data = newData;
        console.log("this.data", this.data)
        Object.assign(targetCache, target);
        console.log("newCacheData", newCacheData)
        this.cacheData = newCacheData;
        console.log("this.cacheData", this.cacheData)
      }
      this.editingKey = '';
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.find(item => key === item.key);
      this.editingKey = '';
      if (target) {
        Object.assign(target, this.cacheData.find(item => key === item.key));
        delete target.editable;
        this.data = newData;
        this.data = []
      }
    },
    //查看录像配置
    goDevChannelRecord() {
      this.$parent.closeRouteViewTab('/record/RecordConfig')
      this.$router.push({
        name: '/systemConfig/RecordConfig',
        params: {
          flag: 'add'
        }
      })
    },
    disabledDate(current) {
      // 限制只能选今天及之后的日期（今天可选中）
      return current && current < moment().subtract(1, 'days').endOf('day')
    },
    goClose() {
      this.$parent.closeRouteViewTab('/record/addrecordtask')
      this.$router.push({
        name: '/record/recordtasklist',
      })
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      let params = this.getQueryParams(); //查询条件
      this.loading = true;
      console.log(params)
      postAction(this.url.list, params).then((res) => {
        if (res.code == "00000") {
          if (!res.data) {
            this.loading = false;
            return
          }
          this.dataSource = res.data.records;
          this.ipagination.total = res.data.total;
        } else {
          this.$message.warning(res.msg);
          // 没有查询到数据，数据初始化
          if (res.code == "A0404") {
            this.dataSource = [];
            this.ipagination.total = 0;
          }
        }
        this.loading = false;
      })
    },
    addRecordTask() {
      let recordTaskItems = [];
      let taskData = this.cacheData;
      taskData.forEach(item => {
        recordTaskItems.push({
          name: item.name,
          cameraId: item.cameraId,
        })
      })
      let params = {
        recordTaskItems: recordTaskItems,
        taskDesc: this.form.getFieldValue('taskDesc'),
        typeId: this.form.getFieldValue('typeId'),

        used: this.form.getFieldValue('used') ? "1" : "0",
        cameraRegionId: this.queryParam.cameraRegionId
      }
      let taskId = this.form.getFieldValue('typeId');
      if (taskId == 0) {
        params.startDateTime=this.form.getFieldValue('rangeValue')[0].format('YYYY-MM-DD HH:mm:ss');
        params.endDateTime=this.form.getFieldValue('rangeValue')[1].format('YYYY-MM-DD HH:mm:ss');
      }
      postAction(this.url.addRecord, params).then((res) => {
        if (res.code == "00000") {
          this.goClose()
        } else {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      })
    },
    getRole() {

    },
    changeTypeId(e) {
      // let typeId = (e.target.value)
      // alert(typeId)
      // // alert(this.form.getFieldValue('typeId'))
      // if (typeId == 0) {
      //   //移除其中的某一项校验
      //   this.$refs['form'].clearValidate()
      // }
      // if (typeId == 4) {
      //   this.$refs['form'].clearValidate()
      // }
    }
    // **************************************************************************************************************

  },
  created() {
    this.form.getFieldDecorator('used', {initialValue: true, preserve: true})
    this.form.getFieldDecorator('typeId', {initialValue: "0", preserve: true})
    this.form.getFieldDecorator('name', {initialValue: "", preserve: true})
    this.form.getFieldDecorator('rangeValue', {initialValue: [], preserve: true})
    this.form.getFieldDecorator('taskDesc', {initialValue: "", preserve: true})
    this.currentIndex = 0
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less'
</style>

